package com.azt.front.action.user;
import com.azt.api.pojo.*;
import com.azt.api.service.MsgConfigService;
import com.azt.api.service.MsgUserService;
import com.azt.api.service.UserService;
import com.azt.front.permission.RequireCompany;
import com.azt.front.permission.RequirePermission;
import com.azt.front.permission.RequireUser;
import com.azt.front.utils.ContextUtil;
import com.azt.model.AjaxJson;
import com.azt.model.page.Pagination;
import com.azt.utils.CommonUtil;
import com.azt.utils.RequestUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/employee")
@RequireCompany
@RequirePermission("employeesManage")
public class EmployeeAction {
		
		private static final Logger LOGGER = Logger.getLogger(EmployeeAction.class);
	
	    @Autowired
	    private UserService userService;
	    
	    @Autowired
	    private MsgConfigService msgConfigService;
	    
	    @Autowired
	    private MsgUserService msgUserService;
	    
	    @RequestMapping("/employee_list")
	    @RequireUser
	    public String showEmployee(HttpServletRequest request, Integer pageNo,  HttpServletResponse response, ModelMap model){
	    	Map<String, String> searchMap = RequestUtils.getSearchMap(request);
	    	String thisCompanyId=ContextUtil.getUser().getCompanyId().toString();
	    	String thisRoleType=ContextUtil.getCurrentRoleType().toString();
	    	searchMap.put("so_companyId", thisCompanyId);
	    	searchMap.put("so_roleType", thisRoleType);
			Pagination pagination = userService.getFrontUserPageByCid(pageNo == null ? 1 : pageNo,8, searchMap);
			model.put("pagination", pagination);
			model.put("applyCount", userService.queryApplyUserCount(thisCompanyId, thisRoleType));
			model.put("pid", ContextUtil.getCompany().getParentId());//是否是子公司
			RequestUtils.MapToModelMap(searchMap, request);
	    	return "employee/employeeNew";
	    }
	    
	    @RequestMapping("/employeeApply_list")
	    @RequireUser
	    public String showApplyEmployee(HttpServletRequest request, Integer pageNo,  HttpServletResponse response, ModelMap model){
	    	Map<String, String> searchMap = RequestUtils.getSearchMap(request);
	    	String thisCompanyId=ContextUtil.getUser().getCompanyId().toString();
	    	String thisRoleType=ContextUtil.getCurrentRoleType().toString();
			Pagination pagination = userService.getApplyEmployee(pageNo == null ? 1 : pageNo,8, thisCompanyId,thisRoleType);
			model.put("pagination", pagination);
			model.put("applyCount", userService.queryApplyUserCount(thisCompanyId, thisRoleType));
			model.put("pid", ContextUtil.getCompany().getParentId());//是否是子公司
			RequestUtils.MapToModelMap(searchMap, request);
	    	return "employee/employeeApply";
	    }
	    
	    @RequireUser
	    @RequestMapping("/employee_page")
	    public ModelAndView showPageEmployee(Integer pageNo,int showType,ModelAndView m){
	    	Map<String, String> searchMap=new HashMap<String,String>();
	    	String thisCompanyId=ContextUtil.getUser().getCompanyId().toString();
	    	String thisRoleType=ContextUtil.getCurrentRoleType().toString();
	    	searchMap.put("so_companyId", thisCompanyId);
	    	searchMap.put("so_roleType", thisRoleType);
	    	m.addObject("applyCount", userService.queryApplyUserCount(thisCompanyId, thisRoleType));
	    	if(showType==1){
	    		Pagination pagination = userService.getFrontUserPageByCid(pageNo == null ? 1 : pageNo,8, searchMap);
				m.addObject("pagination", pagination);
				m.setViewName("employee/employeeList");
	    	}else{
	    		Pagination pagination = userService.getApplyEmployee(pageNo == null ? 1 : pageNo,8, thisCompanyId,thisRoleType);
	    		m.addObject("pagination", pagination);
	    		m.setViewName("employee/employeeApplyList");
	    	}
	    	return m;
	    }
	    
	    @RequireUser
	    @RequestMapping("/queryRoleByCompanyId")
	    @ResponseBody
	    public AjaxJson  queryRoleByCompanyId(Integer requestType){
	    	String thisCompanyId=ContextUtil.getUser().getCompanyId().toString();
	    	String thisRoleType=ContextUtil.getCurrentRoleType().toString();
	    	AjaxJson aj=new AjaxJson();
	    	try {
				 int roleCount=userService.queryRoleByCompanyId(thisCompanyId,thisRoleType);
				 if(roleCount==0){
					 if(requestType==null){
						 aj=AjaxJson.error("您的公司没有创建任何角色，请先去创建一个角色!");
					 }else{
						 aj=AjaxJson.error("该员工无法加入企业，因为您的企业还未创建任何角色");
					 }
				 }
			} catch (Exception e) {
				 e.printStackTrace();
				 aj=AjaxJson.error("系统繁忙");
			}
	    	return aj;
	    }
	    
	    @RequestMapping("/toAddUserView")
	    @RequireUser
	    public String toAddUserView(Model model,Integer roleId){
	    	Integer thisCompanyId=ContextUtil.getUser().getCompanyId();
	    	List<Role> thisroles=userService.getRolesByCompanyId(thisCompanyId,ContextUtil.getCurrentRoleType());
	    	model.addAttribute("firstRole", thisroles.get(0));
	    	model.addAttribute("roles", thisroles);
	    	model.addAttribute("roleId", roleId==null?0:roleId);
	    	return "employee/addEmployeeNew";
	    }
	    
	    @RequestMapping("/validateUser")
	    @ResponseBody
	    @RequireUser
	    public AjaxJson validateAddUser(String login,int ifedit){
	    	AjaxJson aj=new AjaxJson();
	    	Map<String, Object> userParams=new HashMap<String,Object>();
	    	Integer thisCompanyId=ContextUtil.getUser().getCompanyId();
	    	try {
	    		User u=userService.queryUserBylogin(login);
		    	if(u==null){
		    		aj=AjaxJson.success(ifedit==1?"该账号可以修改":"该员工可以添加");
		    		userParams.put("type", "1");
		    	}else {
					if(u.getCompanyId()!=null){
						if(!thisCompanyId.equals(u.getCompanyId())){
							aj=AjaxJson.error(ifedit==1?"无法修改，该账户已经加入其它企业":"无法添加，该账户已经加入其它企业");
						}else{
							aj=AjaxJson.error(ifedit==1?"无法修改，该账号已存在本公司":"无法添加，该员工已存在本公司");
						}
						userParams.put("type", "2");
					}else{
						if(!StringUtils.isNotBlank(u.getRealName())){
							if(u.getMobile()!=null){
								userParams.put("login", u.getMobile().substring(0, 3)+"****"+u.getMobile().substring(7, 11));
							}else{
								userParams.put("login", u.getEmail().substring(0, 3)+"****"+u.getEmail().substring(7, u.getEmail().length()));
							}
						}else{
							userParams.put("login", "*"+u.getRealName().substring(1, u.getRealName().length()));
						}
						aj=AjaxJson.success(ifedit==1?"该账号可以修改":"该员工可以添加");
						userParams.put("type", "3");
						userParams.put("uid", u.getId());
						userParams.put("realName", u.getRealName());
						userParams.put("contactTel", u.getContactTel());
					}
				}
			} catch (Exception e) {
				 e.printStackTrace();
				 aj=AjaxJson.error("系统繁忙");
			}
	    	aj.setAttributes(userParams);
	    	return aj;
	    }
	    
	    @RequestMapping("/doAddUser")
	    @ResponseBody
	    @RequireUser
	    public AjaxJson doAddUser(@RequestBody User user){
	    	AjaxJson aj=new AjaxJson();
	    	Company company=ContextUtil.getCompany();
	    	try {
				 userService.addEmployee(user, company, user.getRoleId(),ContextUtil.getCurrentRole().getCode());
			} catch (Exception e) {
				e.printStackTrace();
				aj=AjaxJson.error("注册失败");
			}
	    	
	    	return aj;
	    }
	    
	    @RequestMapping("/toemployee_edit")
	    @RequireUser
	    public String toEditUser(User user,Model model){
	    	Integer thisCompanyId=ContextUtil.getUser().getCompanyId();
	    	try {
	    		List<Role> thisroles=userService.getRolesByCompanyId(thisCompanyId,ContextUtil.getCurrentRoleType());
	    		User u=userService.getFullUserById(user.getId());
	    		if(!u.getCompanyId().equals(thisCompanyId)){
	    			return "employee/error";
	    		}
	    		model.addAttribute("user", u);
	    		model.addAttribute("uRole", u.getRoles().get(0));
		    	model.addAttribute("roles", thisroles);
			} catch (Exception e) {
				e.printStackTrace();
			}
	    	return "employee/employeeEdit";
	    }
	    
	    @RequestMapping("/doEditUser")
	    @ResponseBody
	    @RequireUser
	    public AjaxJson doEditUser(HttpServletRequest request,@RequestBody User user){
	    	AjaxJson aj=new AjaxJson();
	    	try {
				userService.updateEmpoyee(user,user.getOriginRoleid(),ContextUtil.getCompany(),ContextUtil.getCurrentRole().getCode());
				aj=AjaxJson.success("修改成功！");
			} catch (Exception e) {
				e.printStackTrace();
				aj=AjaxJson.error("修改失败，系统出错");
			}
	    	return aj;
	    }
	    
	    @RequireUser
	    @ResponseBody
	    @RequestMapping("/showAgreeApplyView")
	    public ModelAndView showAgreeApplyView(ModelAndView m,Integer uid,String login,Integer roleId,Integer totype){
	    	Integer thisCompanyId=ContextUtil.getUser().getCompanyId();
	    	try {
	    		List<Role> thisroles=userService.getRolesByCompanyId(thisCompanyId,ContextUtil.getCurrentRoleType());
	    		UserApplyCompany u=userService.getUserApplyCompanyByUid(uid);
				m.addObject("uid", uid);
				m.addObject("login", login);
				m.addObject("roleId", roleId);
				m.addObject("realName", u.getRealName());
				m.addObject("roles", thisroles);
				if(totype==2){
					m.setViewName("employee/agreeApply");
				}else{
					m.setViewName("employee/refuseApply");
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
	    	return m;
	    }
	    
	    @RequestMapping("/doAgreeApplyUser")
	    @ResponseBody
	    @RequireUser
	    public AjaxJson doAgreeApplyUser(@RequestBody UserApplyVO userapply){
	    	AjaxJson aj=new AjaxJson();
	    	try {
	    		 UserApplyCompany u=userService.getUserApplyCompanyByUid(CommonUtil.safeToInteger(userapply.getUserId()));
	    		 if(u!=null){
	    			 User u2= userService.getUserById(CommonUtil.safeToInteger(userapply.getUserId()));
	    			 if(u2.getCompanyId()==null){
	    				 u.setAuditState(1);
			    		 u.setRoleId(CommonUtil.safeToInteger(userapply.getRoleId()));
			    		 userService.agreeUserApply(u);
			    		 aj=AjaxJson.success("员工申请成功");
			    		 
			    		 //短信
			    		 Map<String, String> params=new HashMap<String, String>();
			    		 params.put("companyName", ContextUtil.getCompany().getCompanyName());
			    		 msgConfigService.sendMessage("APPLY_USER", params, null, u.getUserId());
			    		 if("padmin".equals(ContextUtil.getCurrentRole().getCode())){
			    			 msgUserService.insertByUserAndCompany(u.getUserId(), ContextUtil.getCompany().getId());
			    		 }
	    			 }else{
	    				 aj=AjaxJson.error("操作失败,员工已加入另外一家公司");
	    			 }  
	    		 }
			} catch (Exception e) {
				 e.printStackTrace();
				 aj=AjaxJson.error("系统繁忙,申请失败！");
			}
	    	return aj;
	    }
	    
	    @RequireUser
	    @ResponseBody
	    @RequestMapping("/doRefuseApplyUser")
	    public AjaxJson doRefuseApplyUser(UserApplyCompany u){
	    	AjaxJson aj=new AjaxJson();
	    	try {
	    		UserApplyCompany uap=userService.getUserApplyCompanyByUid(u.getUserId());
	    		uap.setAuditOpinion(u.getAuditOpinion());
	    		userService.refuseUserApply(uap);
	    		aj=AjaxJson.success("已成功拒绝");
	    		//短信
	    		Map<String, String> params=new HashMap<String, String>();
	    	    params.put("companyName", ContextUtil.getCompany().getCompanyName());
	    	    params.put("option", u.getAuditOpinion());
	    		msgConfigService.sendMessage("REFUSE_USER", params, null, u.getUserId());
			} catch (Exception e) {
				e.printStackTrace();
				aj=AjaxJson.error("系统繁忙");
			}
	    	return aj;
	    }
	    
	    @RequestMapping("/doDelEmp")
	    @ResponseBody
	    @RequireUser
	    public AjaxJson doDelEmp(Integer uid){
	    	AjaxJson aj=new AjaxJson();
	    	Integer thisCompanyId=ContextUtil.getUser().getCompanyId();
	    	try {
				User thisuser=userService.getFullUserById(uid);
				if(!thisuser.getCompanyId().equals(thisCompanyId)){
					aj=AjaxJson.error("系统繁忙");
					return aj;
				}
				userService.unbindUserFromCompany(uid.toString());
				aj=AjaxJson.success("删除成功");
			} catch (Exception e) {
				e.printStackTrace();
				aj=AjaxJson.error("系统繁忙");
			}
	    	return aj;
	    }
}
